//
//  ZMemberManagerVC.m
//  WeClubs
//
//  Created by Zed Link on 23/4/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZMemberManagerVC.h"
#import "ZClubMemberCell.h"
#import "ZCommentHeader.h"
#import "ZBasePickerVC.h"
#import "ZOwnerClubModel.h"
#import "ZMemberGroupModel.h"
#import "ZClubsListHeaderView.h"
NSString * const MemberManagerHeaderReuseID = @"ZMemberManagerHeaderReuseID";
NSString * const ClubMemberCellReuseID = @"ZClubMemberCellReuseID";

@interface ZMemberManagerVC () <UITableViewDelegate, UITableViewDataSource>

/** 主界面 */
@property ( nonatomic) UITableView *tableView;


//[@"姓名",@"部门",@"年级",@"职位"];
@property(nonatomic)ZClubsListHeaderView *headerView;

//搜索
@property(nonatomic)UISearchBar *searchBar;

@property (strong, nonatomic)NSMutableArray *memberDataArr;
//点击右边索引提示
@property(nonatomic,weak)UILabel *alertLabel;

@property(nonatomic,strong)NSTimer *timer;


//右边索引
@property(nonatomic)NSMutableArray *indexDataArr;

@end

@implementation ZMemberManagerVC

#pragma mark - Life Cycle
- (void)viewDidLoad{

    [super viewDidLoad];

     [self initUI];
   [self loadDataFormNetWork:ZSortType_Initial]; //默认按姓名排序
    
   
}
- (void)zConfigNavigation
{
    [super zConfigNavigation];
    
    [self zAddBackItemWithGesture:YES];
    self.navigationItem.title = @"成员管理";
    self.navigationItem.rightBarButtonItem = [self zNavItemWithImage:@"ic_editmember" shouldOriginal:YES andSelector:@selector(memberManagerAction)];
    
}


#pragma mark - init Methods
-(void)initUI{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view setBackgroundColor:NAVBAR_BG_COLOR];
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.searchBar];
    
    [self.view addSubview:self.headerView];
    
}

#pragma mark - loadData
- (void)loadDataFormNetWork:(ZSortType)type{
 
        [MBProgressHUD zAlertProgress:@"正在加载中"];
        [self.memberDataArr removeAllObjects];
        [self.indexDataArr removeAllObjects];

        NSDictionary *params = @{
                                 @"club_id":@(_clubId),
                                 @"sort_type":@(type),
                                 };
        [HTTPRequest POST:kGet_club_studentsUrl parameter:params success:^(id resposeObject) {
            [MBProgressHUD zAlertHideHUD];
            if ([resposeObject[@"result_code"] integerValue] == ZNetManagerStatusSuccess) {
            
            for (NSDictionary *dict in resposeObject[@"data"][@"groups"]) {
                
                ZMemberGroupModel * model = [[ZMemberGroupModel alloc]initWithDictionary:dict];
                
                model.group_name = dict[@"group_name"];
                [self.indexDataArr addObject:model.group_name];
                [self.memberDataArr addObject:model];
                
            }
                
                [self.tableView reloadData];
            }else{
                [MBProgressHUD zAlertMessage:resposeObject[@"result_msg"] to:self.view afterDelay:1.0];
                
            }
            
        } failure:^(NSError *error) {
            [MBProgressHUD zAlertHideHUD];
        }];

}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.memberDataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ZMemberGroupModel * model = self.memberDataArr[section];
    return model.studentsArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZClubMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:ClubMemberCellReuseID];
    
    ZMemberGroupModel *model = self.memberDataArr[indexPath.section];
    ZStudentModel *studentModel = model.studentsArr[indexPath.row];
    cell.model = studentModel;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZCommentHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:MemberManagerHeaderReuseID];
    header.style = ZTableHeaderStyleDetail;
    ZMemberGroupModel *model = self.memberDataArr[section];
    
    header.alignment = ZTableHeaderAlignmentCenter;
    [header zSetTitle:model.group_name];
    [header zSetBackgroundColor:GENERAL_VIEW_BG_COLOR];
    
    return header;
}
//- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//    
//    return self.indexDataArr;
//    
//}
//-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
//    
//    ZLog(@"===%@  ===%zd",title,index);
//    
//    [self showSelectedTitle:title];
//    return index;
//    
//}

-(void)showSelectedTitle:(NSString*)title{
    
    [self.alertLabel setText:title];
    self.alertLabel.hidden = NO;
    self.alertLabel.alpha = 1.0;
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAnimation:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    
}

-(void)timerAnimation:(NSTimer *)timer{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.25 animations:^{
            self.alertLabel.alpha = 0;
        } completion:^(BOOL finished) {
            self.alertLabel.hidden = YES;
        }];
    });
    
    
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
    {
//        Z_WEAK_SELF
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除操作意味着该成员将退出组织, 请确定!" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"删除该成员" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
        {
            // Todo: 删除某成员
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        
        [self.navigationController presentViewController:alert animated:YES completion:nil];
    }];
    
    UITableViewRowAction *edit = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"职能编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
    {
        // Todo: 编辑职能
        ZBasePickerVC *picker = [ZBasePickerVC zNew];
        picker.doubleCoupleSource = @[
                                      @[@"A", @"B", @"C"],
                                      @[@"D", @"E", @"F"],
                                      ];
        [picker presentPicker];
    }];
    edit.backgroundColor = HIGHTLIGHT_COLOR;
    
    return @[delete, edit];
}



#pragma mark - SEL Methods
- (void)memberManagerAction{
    
}


#pragma mark - Setter && Getter Methods
- (UISearchBar *)searchBar{
    
    if (!_searchBar) {
        _searchBar= [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, Z_SCREEN_WIDTH, 44)];
        [_searchBar setPlaceholder:@"搜索社团成员"];
        [_searchBar setBackgroundColor:GENERAL_VIEW_BG_COLOR];
        [_searchBar setSearchBarStyle:UISearchBarStyleMinimal];
        [_searchBar setSearchFieldBackgroundImage:[UIImage zImageWithColor:NAVBAR_BG_COLOR size:CGSizeMake(self.view.width, 28) andRadius:4] forState:UIControlStateNormal];
    }
    
    return _searchBar;
    
}

- (ZClubsListHeaderView *)headerView{
    
    
    if (!_headerView) {
        _headerView = [[ZClubsListHeaderView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), Z_SCREEN_WIDTH, 40)];
        Z_WEAK_SELF;
        
        _headerView.handlerBtnClickCallBack = ^(UIButton *btn){
            
            [weakSelf loadDataFormNetWork:btn.tag];
        };
    }
    
    return _headerView;
}

-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44+64+50, Z_SCREEN_WIDTH, Z_SCREEN_HEIGHT -(44+64+50) ) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setBackgroundColor:GENERAL_VIEW_BG_COLOR];
        
        _tableView.separatorColor = SEPARATOR_BG_COLOR;
        _tableView.estimatedRowHeight = 88;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        
        [_tableView registerNib:[UINib nibWithNibName:@"ZClubMemberCell" bundle:nil] forCellReuseIdentifier:ClubMemberCellReuseID];
        [_tableView registerClass:[ZCommentHeader class] forHeaderFooterViewReuseIdentifier:MemberManagerHeaderReuseID];

    }
    
    return _tableView;
}

//设置提示的Label
-(UILabel *)alertLabel{
    
    if (!_alertLabel) {
        
        UILabel *alertLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 88, 88)];
        
        alertLabel.center = self.view.center;
        alertLabel.textAlignment = NSTextAlignmentCenter;
        alertLabel.textColor = HIGHTLIGHT_COLOR;
        alertLabel.font =[UIFont systemFontOfSize:15];
        alertLabel.backgroundColor =[UIColor whiteColor];
        alertLabel.layer.cornerRadius = 10;
        alertLabel.layer.masksToBounds =YES;
        alertLabel.layer.borderWidth = 5.0f;
        alertLabel.layer.borderColor =[UIColor grayColor].CGColor;
        [self.navigationController.view addSubview:alertLabel];
        _alertLabel = alertLabel;
        self.alertLabel.hidden = YES;
        
    }
    
    return _alertLabel;
}
- (NSMutableArray *)memberDataArr{

    if (!_memberDataArr) {
        _memberDataArr = [NSMutableArray array];
        
    }
    return _memberDataArr;
}

- (NSMutableArray *)indexDataArr{
    
    if (!_indexDataArr) {
        _indexDataArr =[NSMutableArray array];
        
        
    }
    return _indexDataArr;
    
}

@end
